package com.shuke.sk_worm.tool.hiskpi.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shuke.sk_worm.consts.ShopPlatformEnum;
import com.shuke.sk_worm.domain.HisKpi;
import com.shuke.sk_worm.service.HisKpiService;
import com.shuke.sk_worm.tool.TimeUtil;
import com.shuke.sk_worm.vo.JingdongDataVo;
import com.shuke.sk_worm.vo.ShopInfoListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class JingdongShopImpl extends ShopDataImpl{

    private String dataUrl = "https://kf.jd.com/waiterContrast/workload/queryList?page=1&pageSize=100&startTime=%s&endTime=%s&transferType=1&type=1";

    //销售数据接口
    private String saleUrl = "https://kf.jd.com/waiterContrast/sales/queryList?startTime=2024-05-13&endTime=2024-05-13&page=1&pageSize=15";

    @Autowired
    private HisKpiService hisKpiService;

    private List<HisKpi> getUrlHisData(Date date, String cookie, List<String> shopAccounts, ShopInfoListVo shop){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Long timestamp = date.getTime();
        //将时间转换指定格式的日期
        String terDate = f.format(timestamp);

        String time = sdf.format(timestamp);

        String url = String.format(dataUrl, time, time);

        String data = HttpRequest.get(url).header("Cookie", cookie).execute().body();

        JSONObject result = JSONUtil.parseObj(data);
        List<HisKpi> hisKpis = new ArrayList<>();
        if ("success".equals(result.get("code"))){
            List<JingdongDataVo> dataVos = JSONUtil.toList(JSONUtil.parseArray(result.get("workKpiList")), JingdongDataVo.class);

            dataVos.forEach(his->{
                if (shopAccounts.contains(his.getWaiter())){
                    HisKpi hisKpi = new HisKpi();
                    hisKpi.setStaffName(his.getWaiter()); //客服昵称
                    hisKpi.setStaffUsername(his.getWaiter());
                    hisKpi.setLaborUserAmount(his.getServicedNum()); //人工已接待数量

                    if (his.getSatisfiedRate() != null){
                        hisKpi.setSatisfactionRate(his.getSatisfiedRate());
                        hisKpi.setDissatisfactionRate(TimeUtil.subPercent(his.getSatisfiedRate())); //不满意率
                    }else{
                        hisKpi.setSatisfactionRate("-");
                        hisKpi.setDissatisfactionRate("-"); //不满意率
                    }
                    if (his.getWaiterPhaseNoMore180sResponseRate() != null){
                        hisKpi.setThreeMinResponseConRate(his.getWaiterPhaseNoMore180sResponseRate()); //三分钟人工回复率(3分钟人工回复率（会话）)
                        hisKpi.setThreeMinResponseRate(his.getWaiterPhaseNoMore180sResponseRate());//三分钟响应率(3分钟人工回复率（消息）)
                    }else{
                        hisKpi.setThreeMinResponseConRate("-");
                        hisKpi.setThreeMinResponseRate("-");
                    }
                    hisKpi.setFirstResponseDuration(his.getResponseAvgSpeed()); //首次响应时长
                    hisKpi.setAvgResponseDuration(his.getResponseAvgDuration());//新平均响应时长
                    hisKpi.setInsertTime(terDate);
                    hisKpi.setInsertTimestamp(timestamp);
                    hisKpi.setUserId(shop.getUserId());
                    hisKpi.setUserName(shop.getUserName());
                    hisKpi.setShopId(shop.getId());
                    hisKpi.setShopName(shop.getName());
                    hisKpi.setUserIds(shop.getUserIds());
                    hisKpi.setDeptId(shop.getDeptId());
                    hisKpi.setDeptIds(shop.getDeptIds());
                    hisKpi.setDeptNames(shop.getDeptNames());
                    hisKpi.setPlatform(ShopPlatformEnum.JINGDONG);
                    hisKpi.setBusinessManagerIds(shop.getBusinessManagerIds());
                    hisKpi.setBusinessManagerNames(shop.getBusinessManagerNames());
                    hisKpi.setBaseManagerIds(shop.getBaseManagerIds());
                    hisKpi.setBaseManagerNames(shop.getBaseManagerNames());
                    hisKpis.add(hisKpi);
                }
            });
        }

        return hisKpis;
    }

    @Override
    public void hiskpi(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie, Date startTime){
        for (ShopInfoListVo shop : shopInfoList) {
            if (!shopCookie.containsKey(shop.getId())) {
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //账号信息
            List<String> shopAccounts = shop.getAccountInfos().stream().map(vo->{
                return  vo.getShopAccount().trim();
            }).collect(Collectors.toList());


            //昨日的数据
            List<HisKpi> yesterData = getUrlHisData(startTime, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!yesterData.isEmpty()){
                hisKpiService.batchInsertData(yesterData);
            }

            //24小时前的数据
            Date fourDay = DateUtil.offsetDay(startTime, -1);
            List<HisKpi> fourData =  getUrlHisData(fourDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!fourData.isEmpty()){
                //保存数据
                hisKpiService.batchInsertData(fourData);
            }

            Date eightDay = DateUtil.offsetDay(fourDay, -1);
            List<HisKpi> eightData =  getUrlHisData(eightDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!eightData.isEmpty()){
                //保存数据
                hisKpiService.batchInsertData(eightData);
            }
        }
    }
}
